﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

public partial class Pages_capcha : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        const string chars = "qwertyuiopasdfghjklzxcvbnmQ4WE2RT9YU1P7AF8GH5K3ZXC6VBNM123456789";
        string strCaptcha = "";
        ////////////
        string[] fonts = { "Arial", "Verdana", "Times New Roman" };
        Brush[] brushs = { Brushes.Blue, Brushes.Yellow, Brushes.Red, Brushes.Green };
        Random ran = new Random();
        using (Bitmap bmp = new System.Drawing.Bitmap(120, 40))
        {
            using (Graphics g = Graphics.FromImage(bmp))
            {
                HatchBrush brush = new HatchBrush(HatchStyle.Wave, Color.Black, Color.Silver);
                g.FillRegion(brush, g.Clip);
                for (int i = 0; i < 4; i++)
                {
                    string str = chars[ran.Next(chars.Length)].ToString();
                    strCaptcha += str;
                    Font font = new Font(fonts[ran.Next(fonts.Length)], 20, FontStyle.Bold | FontStyle.Italic);
                    SizeF size = g.MeasureString(str, font);
                    g.DrawString(str, font, brushs[ran.Next(brushs.Length)], i * size.Width + 3, ran.Next(2, 13));
                    font.Dispose();
                }
                brush.Dispose();
                Session["capcha"] = strCaptcha.ToLower();
                Response.ContentType = "image/GIF";
                bmp.Save(Response.OutputStream, ImageFormat.Gif);
            }
        }
    }
}